﻿using System;

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Toggle))]
public class UGUIToggle : MonoBehaviour
{
    public GameObject OnObject { get { return onObject; } }
    public GameObject OffObject { get { return offObject; } }
    public Toggle Toggle { get { return toggle; } }
    public bool isOn { get { return toggle.isOn; } set { toggle.isOn = value; } }

    public Action<object, bool> onValueChangedEvent;

    [SerializeField]
    protected GameObject onObject;

    [SerializeField]
    protected GameObject offObject;

    [SerializeField]
    protected Toggle toggle;

    void Start()
    {
        if (toggle == null)
        {
            toggle = GetComponent<Toggle>();
        }

        toggle.onValueChanged.AddListener(OnValueChange);

        OnValueChange(toggle.isOn);
    }

    void OnDestroy()
    {
        if (toggle != null)
        {
            toggle.onValueChanged.RemoveListener(OnValueChange);
        }
    }

    protected void OnValueChange(bool val)
    {
        DoValueChange(val);

        if (onValueChangedEvent != null)
        {
            onValueChangedEvent(this, val);
        }
    }

    protected virtual void DoValueChange(bool val)
    {
        if (offObject != null)
        {
            offObject.SetActive(!val);
        }

        if (onObject != null)
        {
            onObject.SetActive(val);
        }
    }

    public void SetOnObject(GameObject onObject)
    {
        this.onObject = onObject;
    }

    public void SetOffObject(GameObject offObject)
    {
        this.offObject = offObject;
    }

    public bool interactable
    {
        get { return toggle.interactable; }
        set { toggle.interactable = value; }
    }
}